package com.fhzn.auth.web.request;

import com.alibaba.fastjson.JSONObject;
import com.fhzn.auth.entity.Resource;
import com.fhzn.auth.enums.CommonStatusEnum;
import com.fhzn.commons.toolkit.exception.BuzException;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;

/**
 * @author fhzn
 */
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class ResourceOpRequest extends BaseRequest {

    private Integer id;

    private String name;

    private String code;

    private String parentCode;

    private String resourceUrl;

    private Integer level;

    private Integer resourceType;

    private String resourceExt;

    private Integer sort;

    private String comment;

    private Integer status;

    private String appCode;

    private String icon;


    public void checkAdd() {
        this.checkCommon();
    }

    public void checkUpdate() {
        if (id == null) {
            throw new BuzException("id不能为空");
        }
        this.checkCommon();
    }

    public void checkCommon() {
        int maxSortLength = 9999;
        this.checkBaseParams();
        // 检查url是否合法
        // 检查code是否包含非法字符
        // 检查level与parentCode,只有0级的level才允许parentCode为空
        if (StringUtils.isBlank(appCode)) {
            throw new BuzException("所属应用不能为空");
        }
        if (status == null || !CommonStatusEnum.contains(status)) {
            throw new BuzException("状态位不正确");
        }

        if (sort != null && sort > maxSortLength) {
            throw new BuzException("排序号过长");
        }

    }

    /**
     * 生成发往服务端的query对象
     *
     * @return 资源信息
     */
    public Resource genServiceParam() {
        Resource resource = new Resource();
        resource.setId(this.getId());
        resource.setName(this.getName());
        resource.setCode(this.getCode());
        resource.setParentCode(this.getParentCode());
        resource.setResourceUrl(this.getResourceUrl());
        resource.setLevel(this.getLevel());
        resource.setResourceType(this.getResourceType());
        resource.setResourceUrl(this.getResourceUrl());
        resource.setStatus(this.getStatus());
        resource.setSort(this.getSort());
        resource.setComment(this.getComment());
        resource.setAppCode(this.getAppCode());
        resource.setModifier(this.getHandler());
        JSONObject ext = new JSONObject();
        ext.put("icon", icon);
        if (StringUtils.isNotEmpty(getResourceExt())) {
            ext.put("data", getResourceExt());
        }
        resource.setResourceExt(ext.toJSONString());
        return resource;
    }

    public Resource addGenServiceParam() {
        Resource resource = genServiceParam();
        resource.setCreator(this.getHandler());
        return resource;
    }


}
